package com.lin.common.utils;

import com.google.gson.Gson;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpClientUtils {
    private static Logger log = LoggerFactory.getLogger(HttpClientUtils.class);
    // 池化管理
    private static PoolingHttpClientConnectionManager poolConnManager = null;
    private static Gson gs = new Gson();
    private static CloseableHttpClient httpClient;// 它是线程安全的，所有的线程都可以使用它一起发送http请求

    static {
        try {
            log.info("init Pool SSL");
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            // 配置同时支持 HTTP 和 HTPPS
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
            // 初始化连接管理器
            poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            poolConnManager.setMaxTotal(64);// 同时最多连接数
            // 设置最大路由
            poolConnManager.setDefaultMaxPerRoute(32);
            // 此处解释下MaxtTotal和DefaultMaxPerRoute的区别：
            // 1、MaxtTotal是整个池子的大小；
            // 2、DefaultMaxPerRoute是根据连接到的主机对MaxTotal的一个细分；比如：
            // MaxtTotal=400 DefaultMaxPerRoute=200
            // 而我只连接到http://www.abc.com时，到这个主机的并发最多只有200；而不是400；
            // 而我连接到http://www.bac.com 和
            // http://www.ccd.com时，到每个主机的并发最多只有200；即加起来是400（但不能超过400）；所以起作用的设置是DefaultMaxPerRoute
            // 初始化httpClient
            httpClient = getConnection();

            log.info("init HttpClientTest~~~end");
        } catch (Exception e) {
            log.error("init HttpClient error {}", e);
        }
    }

    public static CloseableHttpClient getConnection() {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();
        CloseableHttpClient httpClient = HttpClients.custom()
                // 设置连接池管理
                .setConnectionManager(poolConnManager)
                .setDefaultRequestConfig(config)
                // 设置重试次数
                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, false)).build();
        return httpClient;
    }

    public static String httpGet(String url,Header... heads) {
        HttpGet httpGet = new HttpGet(url);
        if (heads != null) {
            httpGet.setHeaders(heads);
        }
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            String result = EntityUtils.toString(response.getEntity());
            int code = response.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                return result;
            } else {
                log.error("请求{}返回错误码：{},{}", url, code, result);
                return null;
            }
        } catch (IOException e) {
            log.error("http请求异常，{}", url, e);
        }
        return null;
    }

    public static String httpPost(String uri, Object params, Header... heads) throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(uri);
        String req = gs.toJson(params);
        log.info("req is :\n {}", req);
        StringEntity paramEntity = new StringEntity(gs.toJson(params));
        paramEntity.setContentEncoding("UTF-8");
        paramEntity.setContentType("application/json");
        httpPost.setEntity(paramEntity);
        if (heads != null) {
            httpPost.setHeaders(heads);
        }
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            int code = response.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(response.getEntity());
            log.info("result \n {}", result);
            if (code == HttpStatus.SC_OK) {
                return result;
            } else {
                log.error("请求{}返回错误码:{},请求参数:{},{}", uri, code, params, result);
                return result;
            }
        } catch (IOException e) {
            log.error("收集服务配置http请求异常", e);
        }
        return null;
    }

    public static String post(String uri, Map<String, String> params, Header... heads) throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(uri);
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        if (params.size() != 0) {
            // 将mapdata中的key存在set集合中，通过迭代器取出所有的key，再获取每一个键对应的值
            Set keySet = params.keySet();
            Iterator it = keySet.iterator();
            while (it.hasNext()) {
                String k = it.next().toString();// key
                String v = params.get(k);// value
                nameValuePairs.add(new BasicNameValuePair(k, v));
            }
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        if (heads != null) {
            httpPost.setHeaders(heads);
        }
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            int code = response.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(response.getEntity());
            if (code == HttpStatus.SC_OK) {
                return result;
            } else {
                log.error("post方法：请求{}返回错误码:{},请求参数:{},{}", uri, code, params, result);
                return result;
            }
        } catch (IOException e) {
            log.error("收集服务配置http请求异常", e);
        }
        return null;
    }
}
